<?php
/**
 * Create by 11li
 * Date 2020/1/9
 * Time 11:40
 *
 */

namespace app\common\service;


use app\common\library\Auth;
use app\common\model\Cart;
use app\common\model\Goods;
use think\Exception;

class CartService extends BaseService
{
	
	
	public function add($goodsId, $number, $specId = 0) {
		try {
			if(!$goodsId || !$number) {
				throw new Exception('参数错误');
			}
			
			$goodsModel = new Goods();
			$goods = $goodsModel->alias('g')
				->join('goodsSpec s', 'g.id = s.goods_id and s.id = '.$specId, 'left')
				->where('g.id', $goodsId)
				->field('g.id, g.status, g.stock_number, s.id as spec_id, s.stock_number as spec_number')
				->find();
			
			if(!$goods || $goods['status'] != StatusService::STATUS_NORMAL) {
				throw new Exception('商品不存在或已下架');
			}
			
			if($specId > 0 && !$goods['spec_id']) {
				throw new Exception('规格不正确');
			}
			
			$auth = Auth::instance();
			$userId = $auth->id;
			
			//查找购物车中是否已经存在该商品了
			$model = new Cart();
			$row = $model->getRow($userId, $goodsId, $specId);
			if($row) {
				$res = $model->where(['id' => $row['id']])->setInc('number', $number);
			} else {
				$res = $model->isUpdate(false)
					->save([
						'user_id' => $userId,
						'goods_id' => $goodsId,
						'goods_spec_id' => $specId,
						'number' => $number
					]);
			}
			
			if(!$res) {
				throw new Exception('添加出错');
			}
			
			
			return self::getCartNumber($userId);
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * 获取购物车数量
	 * @param $userId
	 * @return int|string
	 * @throws Exception
	 */
	public static function getCartNumber($userId) {
		$model = new Cart();
		return $model->where(['user_id' => $userId, 'status' => StatusService::STATUS_NORMAL])->count();
	}
	
	public function getCartByUserId($userId)
	{
		$model = new Cart();
		$rows = $model->getCartByUserId($userId);
		$list = [];
		if($rows) {
			foreach ($rows as $row) {
				$key = $row['seller_id'];
				if(!isset($list[$key])) {
					$list[$key] = [
						'seller_id' => $key,
						'seller_name' => $row['seller_name'],
						'goods_list' => []
					];
					
				}
				$list[$key]['goods_list'][] = $row;
			}
		}
		return array_values($list);
	}
	
	/**
	 * 删除购买的记录
	 * @param array $ids
	 * @param $userId
	 * @return false|int
	 */
	public function delByRows(array $ids, $userId)
	{
		$model = new Cart();
		$res = $model->save(
			['status' => StatusService::STATUS_CART_BUY],
			['id' => ['in', $ids], 'user_id' => $userId]
		);
		
		return $res;
	}
}